package leetcode.nTree;

import java.util.ArrayList;
import java.util.List;

public class SolutionServiceImpl implements SolutionService {

    @Override
    public List<Integer> preorder(Node root) {
        List<Integer> res = new ArrayList<>();

        preorderItem(root, res);

        return res;
    }

    private void preorderItem(Node root, List<Integer> res) {
        if(null == root) {
            return;
        }
        res.add(root.val);
        if(null != root.children && !root.children.isEmpty()) {
            for(Node node: root.children) {
                preorderItem(node, res);
            }
        }
    }


    @Override
    public List<Integer> postorder(Node root) {
        List<Integer> res = new ArrayList<>();

        if(null != root) {
            postorderItem(root, res);
            res.add(root.val);
        }

        return res;
    }

    private void postorderItem(Node root, List<Integer> res) {
        if(null == root) {
            return;
        }
        for(Node node: root.children) {
            postorderItem(node, res);
            res.add(node.val);
        }
    }
}
